<script setup>
import { ref, onMounted, watch } from 'vue'
import http from '@/axios/index.js'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue'])

const rolesData = ref([])
const roles = ref([])

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  roles.value = [...newVal]
}, { immediate: true })

// 监听 roles 变化并触发 update:modelValue 事件
watch(roles, (newVal) => {
  emit('update:modelValue', newVal)
}, { deep: true })

// 获取角色列表的函数
const fetchRoleList = async () => {
  try {
    // 直接调用 HTTP 请求获取角色列表
    const response = await http.get('/api/role/list')
    rolesData.value = response.data || response
  } catch (error) {
    console.error('获取角色列表失败:', error)
    // 提供默认角色选项以防 API 失败
    rolesData.value = [
      { id: 1, name: '普通用户' },
      { id: 2, name: '管理员' }
    ]
  }
}

onMounted(() => {
  fetchRoleList()
})
</script>

<template>
  <el-select v-if="rolesData" multiple v-model="roles" placeholder="请选择角色">
    <el-option v-for="item in rolesData" :key="item.id" :label="item.name" :value="item.id"></el-option>
  </el-select>
</template>

<style scoped>
</style>
